package com.dattplace.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.dattplace.model.ReleaseVersion;
import com.dattplace.model.ResultCode;
import com.dattplace.model.ResultData;
import com.dattplace.service.IReleaseVersionService;
import com.dattplace.util.RandomUtil;
import com.dattplace.util.StringUtil;
import com.dattplace.vo.ReleaseVersionVo;
import com.dattplace.vo.SimpleModelVo;

@Controller
@Path("/version")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public class ReleaseVersionController {

	@Autowired
	private IReleaseVersionService releaseVersion;

	@Autowired
	private Mapper mapper;

	@Path("/releaseVersion")
	@POST
	public ResultData<Object> releaseVersion(final ReleaseVersionVo versionVo, @Context HttpServletRequest req) {

		try {
			// 判断是否存在
			if (StringUtil.isEmptyString(versionVo.getAppVersion())) {
				return ResultCode.error("版本号不能为空", null);
			}
			ReleaseVersionVo vo = releaseVersion.queryVersion(versionVo.getAppVersion().trim());

			if (vo != null) {
				return ResultCode.error("版本号已经存在", null);
			}
			versionVo.setReleaseDate(new Date());
			versionVo.setVersionId(new RandomUtil().getRandomId());
			return releaseVersion.releaseVersion(mapper.map(versionVo, ReleaseVersion.class));

		} catch (Exception e) {
			return ResultCode.error("新增标签失败", null);
		}
	}

	@Path("/{versionId}/deleteVersion")
	@GET
	public ResultData<Object> deleteVersion(@PathParam("versionId") final String versionId,
			@Context HttpServletRequest req) {
		try {
			releaseVersion.deleteVersion(versionId);
			return ResultCode.success("删除标签成功", null);
		} catch (Exception e) {
			return ResultCode.error("删除标签失败", null);
		}
	}

	@Path("/queryVersionList")
	@GET
	public ResultData<Object> queryVersionList(@QueryParam("pageNo") final int pageNo,
			@QueryParam("pageSize") final int pageSize, @QueryParam("keyWord") final String keyWord,
			@Context HttpServletRequest req) {
		try {
			SimpleModelVo vo = new SimpleModelVo();
			List<ReleaseVersionVo> list = releaseVersion.queryVersionList(pageNo, pageSize, keyWord);
			vo.setVersionList(list);
			vo.setCount(releaseVersion.queryAllVersionCount(keyWord));
			return ResultCode.success("查询成功", vo);
		} catch (Exception e) {
			return ResultCode.error("查询标签失败", null);
		}
	}
}
